<?php
/**
 * FastApp.
 * 8/22/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Marketing\Crontab;

use App\Game\Job\LottoJob;
use App\Marketing\Model\MarketingLotto;
use App\Marketing\Model\MarketingLottoOpen;
use Carbon\Carbon;
use Hyperf\Crontab\Annotation\Crontab;

class LottoCrontab
{
//    #[Crontab(name: "LottoOpen", rule: "* * * * *", memo: "彩票开奖任务")]
    public function open(): void
    {
        $res = MarketingLotto::query()->where(['status' => 1])->get();
        $t = Carbon::now();
        foreach ($res as $lotto) {
            if ($lotto->open_at) {
                if (MarketingLottoOpen::query()->where(['lotto_id' => $lotto->id, 'periods' => $lotto->periods])->exists()) continue;
                $open_at = Carbon::createFromTimestamp($lotto->open_at);
                $s = 0;
                if ($lotto->open_type == 1 && $t->minute == $open_at->minute) $s = 1;
                if ($lotto->open_type == 2 && $t->hour == $open_at->hour) $s = 1;
                if ($lotto->open_type == 3 && $t->day == $open_at->day && $t->hour == $lotto->open_hour) $s = 1;
                //开奖
                if ($s) {
                    $no = drawDoubleColorBall($lotto->groups);
                    $up['status'] = 2;
                    $lotto->update($up);
                    MarketingLottoOpen::query()->create(['lotto_id' => $lotto->id, 'periods' => $lotto->periods, 'no' => $no]);
                    fastapp_queue_push(new LottoJob($lotto->id, $lotto->periods, $no));
                }
            }
        }
    }

//    #[Crontab(name: "LottoStart", rule: "*/2 * * * *", memo: "彩票当期开启")]
    public function start(): void
    {
        $res = MarketingLotto::query()->where(['status' => 2])->get();
        foreach ($res as $lotto) {
            $open_at = 0;
            if ($lotto->open_type == 1) $open_at = Carbon::now()->addMinutes($lotto->open_time)->getTimestamp();
            if ($lotto->open_type == 2) $open_at = Carbon::now()->addHours($lotto->open_time)->getTimestamp();
            if ($lotto->open_type == 3) $open_at = Carbon::now()->addDays($lotto->open_time)->getTimestamp();
            $lotto->update(['status' => 1, 'periods' => $lotto->periods + 1, 'open_at' => $open_at]);
        }
    }
}